package multithread.thread.chongrusuo;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/*8
使用传统的
 */
public class MyLock implements Lock {
	
	private  boolean isLocked = false;

	//可重入锁，有两个组成，lockBy 和lockCount;
	private Thread lockBy = null;
	
	private int lockCount = 0;

	//synchronized 完毕之后，会把内存里面的变量同步到主内存去
	//进入的时候会从主内存中拿
	//其他进入的要等待。第一个进来的不等待，其他的要等待。
	//其他线程的唤醒，必须等拿到锁的线程调用Unlock功能。

	//synchronized + wait+ nofity 做通信。
	// 	@Override
	public synchronized void lock() {
		// ...
		Thread currentThread = Thread.currentThread(); // Thread-0
		while (isLocked && currentThread != lockBy)//可重入的，如果当前线程已经拿到锁了，就不等待。
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		isLocked = true;
		lockBy = currentThread;
		lockCount ++; // 1   2
	}
	
	@Override
	public synchronized void unlock() {
		if(lockBy == Thread.currentThread()) {//只有锁的持有者才能释放
			lockCount --;  // 1  0
			
			if(lockCount == 0) {
				notify();
				isLocked = false;
			}
		}
	}

	@Override
	public void lockInterruptibly() throws InterruptedException {
		
	}

	@Override
	public boolean tryLock() {
		return false;
	}

	@Override
	public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
		// TODO Auto-generated method stub
		return false;
	}

	

	@Override
	public Condition newCondition() {
		// TODO Auto-generated method stub
		return null;
	}

}
